package com.myway.service.payment.TBCPay.impl;

import com.myway.core.util.HttpClientUtil;
import com.myway.dao.FlyOrderMapper;
import com.myway.dao.FlyOrderPaymentMapper;
import com.myway.dao.PaymentMapper;
import com.myway.dao.TbcResultCodeMapper;
import com.myway.dto.common.JsonData;
import com.myway.dto.common.ResultEntity;
import com.myway.dto.vo.FlySegmentVo;
import com.myway.pojo.*;
import com.myway.service.TicketService;
import com.myway.service.payment.Oceanpayment.TBCService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by qianmi-05 on 2018/9/19.
 */
@Service
public class TBCPayImpl extends DefaultHttpClient implements TBCService {

    @Autowired
    private FlyOrderMapper flyOrderMapper;

    @Autowired
    private PaymentMapper paymentMapper;

    @Autowired
    private FlyOrderPaymentMapper flyOrderPaymentMapper;

    @Autowired
    private TbcResultCodeMapper tbcResultCodeMapper;

    @Autowired
    private TicketService ticketService;

    @Override
    public String TBCToPay(String orderid) {
        if(StringUtils.isEmpty(orderid)){
            return  null;
        }
        FlyOrder flyOrder = flyOrderMapper.selectByPrimaryKey(Long.parseLong(orderid));
        String orderCurrenry = flyOrder.getOrderCurrenry();
        String currency="";
        if(orderCurrenry.equals("EUR")){
            currency="978";
        }else if(orderCurrenry.equals("USD")){
            currency="840";
        }else if(orderCurrenry.equals("CNY")){
            currency="156";
        }else if(orderCurrenry.equals("GEL")){
            currency="981";
        }
        double totalPriceDou = flyOrder.getTotalPrice() * 100;
        int totalPriceInt = (new Double(totalPriceDou)).intValue();
        String totalPrice = String.valueOf(totalPriceInt);
        //测试数据
        String contactName = flyOrder.getContactName();
        if(!StringUtils.isEmpty(contactName)&&contactName.equals("Yang Yuezhang")){
            totalPrice="1";
        }
//        currency="981";
        String params = "command=v&amount="+totalPrice+"&currency="+currency+"&client_ip_addr=47.75.92.162&language=EN&description=UFCTEST&msg_type=SMS";

        Map<String,String> map=new HashMap<String,String>();
        map.put("params",params);

        String httpsUrl = "https://ecommerce.ufc.ge:18443/ecomm2/MerchantHandler";
        String transactionId = HttpClientUtil.doPost("http://47.75.92.162:48082/tbcPay.php?params="+params, map);
        String transactionIdReplace = transactionId.replaceAll("TRANSACTION_ID:", "");
        String transId = transactionIdReplace.trim();
        return transId;
    }

    /**
     * 根据TransId 获取返回结果
     * @param transId
     * @return
     */
    @Override
    public String callBackByTransId(String transId) {
        if(StringUtils.isEmpty(transId)){
            return  null;
        }
        try {
            transId=URLEncoder.encode(transId,"UTF-8");
            String params ="command=c&trans_id="+transId+"&client_ip_addr=47.75.92.162";
            Map<String,String> map=new HashMap<String,String>();
            map.put("params",params);
            String httpsUrl = "https://ecommerce.ufc.ge:18443/ecomm2/MerchantHandler";
            String result= HttpClientUtil.doPost("http://47.75.92.162:48082/tbcPay.php?params="+params, map);
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
         return null;
    }

    @Override
    public String addTbcPaymentInfo(String orderId,String transId,String  result,String result_code,String DSECURE,String RRN,String APPROVAL_CODE,String BANK_ID,String callBackResultStr,String firstTransId) {
        FlyOrder flyOrder = flyOrderMapper.selectByPrimaryKey(Long.parseLong(orderId));
        if(flyOrder==null){
            return  "error";
        }
        Payment payment=new Payment();
        payment.setPayType("tbc");
        payment.setAction("pay");//机票支付
        payment.setAmount(new BigDecimal(flyOrder.getTotalPrice()));
        payment.setPayTime(new Date());
        payment.setCurrency(flyOrder.getCurrency());
        payment.setPayer(flyOrder.getContactName());
        payment.setBankId(BANK_ID);
        payment.setTbc3dsecure(DSECURE);
        payment.setTbcApprovalCode(APPROVAL_CODE);
        payment.setTbcResultCode(result_code);
        payment.setTbcRrn(RRN);
        payment.setRemarks(callBackResultStr);
        payment.setLastTransactionId(transId);
        payment.setTransactionId(firstTransId);
        if(result!=null&&result.equals("OK")){
            payment.setPayStatus("PAID");
        }else{
            payment.setPayStatus("FAIL");
        }
        int paymentNum = paymentMapper.insertSelective(payment);
        if(paymentNum>0){
            FlyOrderPayment flyOrderPayment=new FlyOrderPayment();
            flyOrderPayment.setPaymentId(payment.getId());
            flyOrderPayment.setAmount(new BigDecimal(flyOrder.getTotalPrice()));
            flyOrderPayment.setOrderNo(flyOrder.getId());
            int insertSelective = flyOrderPaymentMapper.insertSelective(flyOrderPayment);
            if(insertSelective<0){
                return  "error";
            }
        }else{
            return "error";
        }

        return "success";
    }

    @Override
    public FlyOrder selectByOrderId(String id) {
        if(id != null && id != ""){
            FlyOrder flyOrder =  flyOrderMapper.selectByPrimaryKey(Long.parseLong(id));
            return flyOrder;
        } else {
            return null;
        }

    }

    @Override
    public TbcResultCode getTbcResultCode(String resultCode) {
        if(StringUtils.isEmpty(resultCode)){
            return null;
        }
        TbcResultCode tbcResultCode = tbcResultCodeMapper.selectByPrimaryKey(resultCode);
        return tbcResultCode;
    }

    @Override
    public FlyOrder getOrderByFirstTransId(String transId) {
        if(StringUtils.isEmpty(transId)){
            return null;
        }
        List<FlyOrder> FlyOrderList = flyOrderMapper.getOrderByFirstTransId(transId);
        if(FlyOrderList.size()>0){
           return FlyOrderList.get(0);
        }
        return null;
    }

    public ResultEntity TBCOKCallBack(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> resultMap = new HashMap<String, Object>();

        String[] trans_ids = parameterMap.get("trans_id");
        if (trans_ids == null && trans_ids.length <= 0) {
            return ResultEntity.fail("trans_ids Valye is null");
        }
        String lastTrans_id = trans_ids[0];
        System.out.println("=====@@@=====FlyaymentController TBCOKCallBack=======>>lastTrans_id" + lastTrans_id);
        String callBackResultStr = callBackByTransId(lastTrans_id);
        System.out.println("=====@@@======FlyaymentController TBCOKCallBack=======>>>======@@@@===pay info callBackResultStr===" + callBackResultStr + "@@@@==================");
        callBackResultStr = callBackResultStr.replaceAll("(\r\n|\r|\n|\n\r)", "<br>");
        //当返回 ERROR 直接返回
        String[] resultError = callBackResultStr.split(":");
        String s1 = resultError[0];
        if (callBackResultStr == null || s1.equals("ERROR")) {
            System.out.println("===========@@@@====FlyaymentController TBCOKCallBack=======>>>======@@@@===支付返回的信息是error信息");
            return ResultEntity.fail("pay info return null");
        }

        Map<String, String> callBackMap = new HashMap<String, String>();
        String[] data1 = callBackResultStr.split("<br>");
        if (data1 != null && data1.length > 0) {
            for (String s : data1) {
                String[] data2 = s.split(":");
                if (data2 != null && data2.length > 0)
                    callBackMap.put(data2[0].trim(), data2[1].trim());
            }
        }
        String result = callBackMap.get("RESULT"), result_code = callBackMap.get("RESULT_CODE"), DSECURE = callBackMap.get("3DSECURE"), RRN = callBackMap.get("RRN"), APPROVAL_CODE = callBackMap.get("APPROVAL_CODE"), BANK_ID = callBackMap.get("CARD_NUMBER");
        FlyOrder flyOrderTransId = getOrderByFirstTransId(lastTrans_id);
        if(flyOrderTransId==null){
            System.out.println("====@@@@======FlyaymentController TBCOKCallBack=======>>>lastTrans_id There is no query order");
            return ResultEntity.fail("lastTrans_id There is no query order ");
        }
        //String orderId = String.valueOf(request.getSession().getAttribute("orderId"));
        String orderId =String.valueOf(flyOrderTransId.getId());
        String firstTransId = request.getSession().getAttribute("firstTransId").toString();
        System.out.println("====@@@@======FlyaymentController TBCOKCallBack=======>>> callBackResultStr slipt解析的结果是=====>result =" + result + ",   result_code=" + result_code + ",   DSECURE=" + DSECURE + ",    RRN=" + RRN + ",   APPROVAL_CODE=" + APPROVAL_CODE + ",    BANK_ID=" + BANK_ID + ",    orderId=" + orderId);
        String paymentResult = addTbcPaymentInfo(orderId, lastTrans_id, result, result_code, DSECURE, RRN, APPROVAL_CODE, BANK_ID, callBackResultStr, firstTransId);
        if (paymentResult.equals("error")) {
            System.out.println("FlyaymentController TBCOKCallBack=======>>>======@@@@===添加支付信息失败");
        }

        FlyOrder flyOrder = selectByOrderId(orderId);
        resultMap.put("$order_number", flyOrder.getOrderId());
        resultMap.put("$order_amount", flyOrder.getTotalPrice() + "");
        resultMap.put("$order_currency", flyOrder.getCurrency());

        if (result != null && result.equals("FAILED")) {
            TbcResultCode tbcResultCode = getTbcResultCode(result_code);
            return ResultEntity.fail("Pay FAILED Return Code is" + tbcResultCode.getMsgFull());
        } else if (result != null && result.equals("OK")) {
            //修改订单支付状态
            FlyOrder flyOrderInfo = new FlyOrder();
            flyOrderInfo.setId(Long.parseLong(orderId));
            flyOrderInfo.setOrderStatus("HP");
            flyOrderMapper.updateByPrimaryKeySelective(flyOrderInfo);
            //出票
            JsonData jsonData = ticketService.handleTicket(flyOrder.getOrderId());

            //添加积分
           /* TabMembIntegral tabMembIntegral = new TabMembIntegral();
            TabMemberInfo member = (TabMemberInfo)request.getSession().getAttribute("member");
            tabMembIntegral.setMembId(member.getMembId());
            tabMembIntegral.setMembLoginName(member.getMembEnSurname() + member.getMembEnName());
            tabMembIntegral.setOrderNo(orderId);
            integralService.distanceToIntegral(tabMembIntegral,orderId);*/

            //发送邮件
           /* JsonData FlyPassengerData = orderService.selectFlyPassengeByOrderId(flyOrder.getId() + "");
            List<FlyPassenge> flyPassengeList = (List<FlyPassenge>) FlyPassengerData.getData();
            JsonData FlySegmentData = orderService.selectFlySegmentByOrderId(flyOrder.getId() + "");
            List<FlySegmentVo> FlySegmentList = (List<FlySegmentVo>) FlySegmentData.getData();
            String contactEmail = flyOrder.getContactEmail();
            String emailContext = JoiningTogether(flyOrder, flyPassengeList, FlySegmentList);
            ResultEntity resultEmail = null;
            System.out.println("============》》》emailContext======" + emailContext);*/

            return ResultEntity.success("pay success");
        } else {
            return ResultEntity.success("Returns an empty or parsing error");
        }

    }

}
